﻿using Server.Framework.Service;
using Server.OptExp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.Service
{
    /// <summary>
    /// Author: Leil
    /// Description: LoginLogService
    /// CreateTime: 2020/6/9 11:12:03
    /// </summary>
    public class LoginLogService
    {
        private static readonly object obj = new object();
        private static LoginLogService instance;
        private LoginLogService() { }

        public static LoginLogService Instance()
        {
            if (instance == null)
            {
                lock(obj)
                {
                    if (instance == null)
                    {
                        instance = new LoginLogService();
                    }
                }
            }
            return instance;
        }


        /// <summary>
        /// 添加登录日志任务
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="ipStr">登录IP</param>
        public void AddLoginLog(int userId, string ipStr)
        {
            string sql = $@"INSERT INTO SYS_LOGIN_LOG ( ID, USER_ID, LOGIN_TIME, LOGIN_IP )
VALUES
	( seq_login_log.NEXTVAL, {userId}, SYSDATE, '{ipStr}' )";
            try
            {
                DBService.Instance().ExecuteNonQuery(sql, res => {
                    if (res > 0)
                    {
                        Console.WriteLine($"{userId}:{ipStr}登录日志写入成功");
                    }
                });
            }
            catch (CommonOptException e)
            {
                Console.WriteLine(e.Message);
            }
        }


        /// <summary>
        /// 添加登出日志任务
        /// </summary>
        /// <param name="userId">用户ID</param>
        public void UpdateLogoutLog(int userId)
        {
            string sql = $@"UPDATE SYS_LOGIN_LOG 
SET LOGOUT_TIME = SYSDATE 
WHERE
	ID = (
SELECT
	t.ID 
FROM
	( SELECT SYS_LOGIN_LOG.*, ( row_number ( ) over ( PARTITION BY USER_ID ORDER BY LOGIN_TIME DESC ) ) AS ROWFLAG FROM SYS_LOGIN_LOG ) t 
WHERE
	USER_ID = {userId} 
	AND ROWFLAG = 1 
	)";
            try
            {
                DBService.Instance().ExecuteNonQuery(sql, res => {
                    if (res > 0)
                    {
                        Console.WriteLine($"{userId}登出日志写入成功");
                    }
                });
            }
            catch (CommonOptException e)
            {
                Console.WriteLine(e.Message);
            }
        }



    }
}
